package com.example.exam.user.controller;

import com.example.exam.authorization.service.AuthorizationService;
import com.example.exam.common.ResultBean;
import com.example.exam.common.ResultBeanCodeEnum;
import com.example.exam.db.PageInfoBean;
import com.example.exam.post.model.PostBean;
import com.example.exam.post.service.PostService;
import com.example.exam.staff.model.StaffBean;
import com.example.exam.staff.service.StaffService;
import com.example.exam.sysRole.model.SysRoleBean;
import com.example.exam.sysRole.service.SysRoleService;
import com.example.exam.user.model.UserBean;
import com.example.exam.user.model.UserRoleBean;
import com.example.exam.user.service.UserRoleService;
import com.example.exam.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    AuthorizationService authorizationService;
    @Autowired
    StaffService staffService;
    @Autowired
    PostService postService;
    String base_path="/user/";
    @GetMapping("/toUser")
        /** 
            * @Description:  去用户信息列表页面
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toUser(HttpServletRequest request){
        HttpSession session=request.getSession();
        Integer userId=(Integer) session.getAttribute("id");
        List<UserRoleBean> list=userRoleService.authorization(userId);
        if(list!=null){
            for (int i=0;i<list.size();i++){
                if("SysUser|toEdit".equals(list.get(i).getPre())){
                    request.setAttribute("update",list.get(i));
                }else if("SysUser|toDelete".equals(list.get(i).getPre())){
                    request.setAttribute("delete",list.get(i));
                }else if("SysUser|toGrant".equals(list.get(i).getPre())){
                    request.setAttribute("grant",list.get(i));
                }else if ("SysUser|toAdd".equals(list.get(i).getPre())){
                    request.setAttribute("add",list.get(i));
                }
            }
        }
        String name=(String)session.getAttribute("username");
        Integer id=(Integer)session.getAttribute("id");
        request.setAttribute("name",name);
        String post=authorizationService.findPost(id);
        if (post!=null){
            if("八岗".equals(post)||"七岗".equals(post)){
                post="八岗";
            }else{
                post=null;
            }
        }
        Integer num=authorizationService.findRole(id);
        request.setAttribute("post",post);
        request.setAttribute("num",num);
        return base_path+"user";
    }
    @GetMapping("/toMain")
        /** 
            * @Description:去主页
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toMain(HttpServletRequest request){
        HttpSession session=request.getSession();
        Integer userId=(Integer) session.getAttribute("id");
        List<UserRoleBean> list=userRoleService.authorization(userId);
        if(list!=null){
            for (int i=0;i<list.size();i++){
                if("SysUser|toSelect".equals(list.get(i).getPre())){
                    request.setAttribute("sysUser",list.get(i));
                }else if("SysRole|toSelect".equals(list.get(i).getPre())){
                    request.setAttribute("sysRole",list.get(i));
                }else if("SysResource|toSelect".equals(list.get(i).getPre())){
                    request.setAttribute("sysResource",list.get(i));
                }else if ("SysDict|toSelect".equals(list.get(i).getPre())){
                    request.setAttribute("sysDict",list.get(i));
                }else if ("SysPost|toSelect".equals(list.get(i).getPre())){
                    request.setAttribute("sysPost",list.get(i));
                }
            }
        }
        String name=(String)session.getAttribute("username");
        Integer id=(Integer)session.getAttribute("id");
        request.setAttribute("name",name);
        String post=authorizationService.findPost(id);
        if (post!=null){
            if("八岗".equals(post)||"七岗".equals(post)){
                post="八岗";
            }else{
                post=null;
            }
        }
        Integer num=authorizationService.findRole(id);
        request.setAttribute("post",post);
        request.setAttribute("num",num);
        return "/main/main";
    }
    @GetMapping("/toLog")
        /** 
            * @Description:  去日志列表页面
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toLog(HttpServletRequest request){
        HttpSession session=request.getSession();
        Integer userId=(Integer) session.getAttribute("id");
        List<UserRoleBean> list=userRoleService.authorization(userId);
        if(list!=null){
            for (int i=0;i<list.size();i++){
                // System.out.println("权限是"+list.get(i).getPre());
                if("SysLog|toUpdate".equals(list.get(i).getPre())){
                    request.setAttribute("update",list.get(i));
                }else if("SysLog|toDelete".equals(list.get(i).getPre())){
                    request.setAttribute("delete",list.get(i));
                }else if("SysLog|toGrant".equals(list.get(i).getPre())){
                    request.setAttribute("grant",list.get(i));
                }else if ("SysLog|toAdd".equals(list.get(i).getPre())){
                    request.setAttribute("add",list.get(i));
                }
            }
        }
        return "/logInfo/Log";
    }
    @PostMapping("/list")
    @ResponseBody
        /** 
            * @Description:  去列表信息页面
            * @Param: [request, limit, page] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean list(HttpServletRequest request, Integer limit,Integer page){
        String loginName=request.getParameter("name");
        HttpSession session=request.getSession();
        Integer id=(Integer) session.getAttribute("id");
        Integer row=authorizationService.findRole(id);
        ResultBean resultBean=new ResultBean();
        try{
            PageInfoBean pageInfoBean=userService.list(limit,page,loginName,row,id);
            resultBean.fillData(pageInfoBean);
            resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
        }catch(Exception e){
            resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            e.fillInStackTrace();
        }
        return resultBean;
    }
    @GetMapping("/toAdd")
        /** 
            * @Description:  去添加用户页面
            * @Param: [] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toAdd(){
        return base_path+"add";
    }
    @PostMapping("/add")
    @ResponseBody
        /** 
            * @Description:  添加用户信息
            * @Param: [userBean, request] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean add(UserBean userBean,HttpServletRequest request){
        ResultBean result = new ResultBean();
        if(userService.selectId(userBean.getLogin_name())==0&&userService.selectId(userBean.getTel())==0){
            userService.entryptPassword(userBean);
            userBean.setCreate_time(new Date());
            userBean.setLogin_time(new Date());
            HttpSession session=request.getSession();
            Integer id=(Integer)session.getAttribute("id");
            userBean.setCreate_user(id);
            Random r=new Random();
            Integer head=r.nextInt(4)+1;
            userBean.setHead(head+".jpg");
            userBean.setState(1);
            try {
                Integer i=userService.insertUser(userBean);
                result.fillData(i);
                result.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                result.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                result.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            }
        }else{
            result.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
            result.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
        }
        return result;
    }
    @GetMapping("/toEdit")
        /** 
            * @Description:  去修改用户信息页面
            * @Param: [id, request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toEdit(Integer id,HttpServletRequest request){
        UserBean userBean=userService.selectOneUser(id);
        request.setAttribute("userBean",userBean);
        return base_path+"edit";
    }
    @GetMapping("/edit")
    @ResponseBody
        /** 
            * @Description: 编辑用户信息
            * @Param: [userBean] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean edit(UserBean userBean){
        ResultBean resultBean=new ResultBean();
        userBean.setState(1);
        try{
            Integer i=userService.updateUser(userBean);
            if(i>0){
                resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
            }else{
                resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            }
        }catch (Exception e){
            e.fillInStackTrace();
            resultBean.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
        }
        return resultBean;
    }
    @GetMapping("/productPwd")
        /** 
            * @Description:  生产初始密码
            * @Param: [response, request] 
            * @return: void 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public void productPwd(HttpServletResponse response, HttpServletRequest request){
        try {
            response.getWriter().write("12345678qy");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/toGrant")
        /** 
            * @Description:  去授权管理页面
            * @Param: [request, id] 
            * @return: java.lang.Object 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public Object toGrant(HttpServletRequest request,Integer id) {
        List<SysRoleBean> roleBeans = sysRoleService.getRoleList(id);
        request.setAttribute("roleBeans",roleBeans);
        request.setAttribute("userId",id);
        return base_path+"userGrant";
    }
    @PostMapping("/grant")
    @ResponseBody
        /** 
            * @Description:  权限管理role_user表添加
            * @Param: [request, roleIds, userId] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean grant(HttpServletRequest request,
                            @RequestParam(value = "roleIds[]",required=false) Integer[] roleIds, Integer userId) {
        ResultBean resultBean  = new ResultBean();
        try {
            Integer rows=userRoleService.save(roleIds, userId,request);
            if(rows==0) {
                resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            }else {
                resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
            resultBean.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
        }
        return resultBean;
    }
    /**
     * @Description:删除用户信息
     * @Param: [id]
     * @return: com.example.exam.common.ResultBean
     * @Author: xhw
     * @Date: 2021/7/26
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResultBean delete(Integer id){
        ResultBean resultBean=new ResultBean();
        try{
            Integer i=userService.delectUser(id);
            if(i>0){
                resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
            }else{
                resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            }
        }catch (Exception e){
            e.fillInStackTrace();
            resultBean.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
        }
        return resultBean;
    }
    @RequestMapping("/toDelete")
    @ResponseBody
        /** 
            * @Description:批量删除用户信息
            * @Param: [request] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean toDelete(HttpServletRequest request) {
        ResultBean result = new ResultBean();
        String role_id  = request.getParameter("id");
        //System.out.println("ids"+role_id);
        try {
            Integer deleState = null;
            if(StringUtils.isNotEmpty(role_id)) {
                int[] roleIds = null;
                String[] ids = role_id.split(",");
                roleIds = new int[ids.length];
                for(int i=0;i<ids.length;i++){
                    roleIds[i]=Integer.parseInt(ids[i]);
                }
                for(int i = 0; i < roleIds.length; i++) {
                    deleState = userService.delectUser(roleIds[i]);
                }
                result.fillData(deleState);
                result.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                result.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
            }else {
                result.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                result.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
            }
            result.fillData(deleState);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
            result.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
        }
        return result;
    }
    @GetMapping("/toOut")
        /** 
            * @Description:  退出系统
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toOut(HttpServletRequest request){
        Enumeration em = request.getSession().getAttributeNames();
        while(em.hasMoreElements()){
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return base_path+"login";
    }
    @GetMapping("/toLogin")
        /** 
            * @Description:  去登录页面/首页
            * @Param: [] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toLogin(){
        return base_path+"login";
    }
    @GetMapping("/head")
    @ResponseBody
        /** 
            * @Description:  将头像信息传至主页
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String head(HttpServletRequest request){
        HttpSession session=request.getSession();
        String head=(String) session.getAttribute("head");
        return head;
    }
    @GetMapping("/toEditPwd")
        /** 
            * @Description:  去修改密码界面
            * @Param: [] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toEditPwd(){
        return "/main/editPwd";
    }
    @PostMapping("/editPwd")
    @ResponseBody
        /** 
            * @Description:修改密码
            * @Param: [newPwd, oldPwd, request] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean editPwd(String newPwd,String oldPwd,HttpServletRequest request){
        ResultBean resultBean=new ResultBean();
        try{
            HttpSession session=request.getSession();
            Integer id=(Integer)session.getAttribute("id");
            UserBean ub=userService.selectOneUser(id);
            String pwd=userService.entryptPassword(oldPwd,ub.getSalt());
            if(pwd.equals(ub.getPassword())){
                UserBean userBean=new UserBean();
                userBean.setPassword(newPwd);
                userBean.setId(id);
                userService.entryptPassword(userBean);
                Integer i=userService.editPwd(userBean.getPassword(),userBean.getSalt(),userBean.getId());
                if(i>0){
                    resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
                    resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
                }else{
                    resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                    resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
                }
            }else{
                resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
                resultBean.setMsg("原密码错误");
            }
        }catch(Exception e){
            e.fillInStackTrace();
            resultBean.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
        }
        return resultBean;
    }
    @PostMapping("/login")
    @ResponseBody
        /** 
            * @Description:  用户登录
            * @Param: [uib, request] 
            * @return: com.example.exam.common.ResultBean 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public ResultBean login(UserBean uib, HttpServletRequest request){
        ResultBean resultBean=new ResultBean();
        Integer count=userService.login(uib);
        if(count==1){
            HttpSession session=request.getSession();
            session.setAttribute("username",uib.getLogin_name());
            Integer id=userService.selectId(uib.getLogin_name());
            session.setAttribute("id",id);
            UserBean uib2=userService.selectOneUser(id);
            uib2.setLogin_time(new Date());
            userService.updateLoginTime(uib2);
            session.setAttribute("head","/system/images/"+uib2.getHead());
            resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
        }else{
            resultBean.setCode(ResultBeanCodeEnum.OPERA_FAIL.getCode());
            resultBean.setMsg(ResultBeanCodeEnum.OPERA_FAIL.getMsg());
        }
        return resultBean;
    }
    @GetMapping("/toMyself")
        /** 
            * @Description:查看个人资料
            * @Param: [request] 
            * @return: java.lang.String 
            * @Author: xhw
            * @Date: 2021/7/26 
            */ 
    public String toMyself(HttpServletRequest request){
        HttpSession session=request.getSession();
        Integer id=(Integer) session.getAttribute("id");
        UserBean userBean=userService.selectOneUser(id);
        Integer staffId=staffService.findStaffId(id);
        StaffBean staffBean=staffService.findById(staffId);
        if(staffBean!=null){
            PostBean postBean=postService.findById(staffBean.getPost());
            staffBean.setpName(postBean.getName());
        }
        request.setAttribute("userBean",userBean);
        request.setAttribute("staffBean",staffBean);
        return "/main/myself";
    }
    @PostMapping("/restPwd")
    @ResponseBody
    public ResultBean restPwd(Integer id){
        ResultBean resultBean=new ResultBean();
        UserBean userBean=new UserBean();
        userBean.setId(id);
        userBean.setPassword("12345678qy");
        userService.entryptPassword(userBean);
        userService.editPwd(userBean.getPassword(),userBean.getSalt(),userBean.getId());
        return resultBean;
    }
}
